package com.hongshu.web.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hongshu.common.core.enums.ConfigKeyEnum;
import com.hongshu.common.core.enums.OssProviderEnum;
import com.hongshu.common.core.enums.SmsProviderEnum;
import com.hongshu.common.core.utils.StringUtils;
import com.hongshu.web.domain.dto.*;
import com.hongshu.web.domain.entity.*;
import com.hongshu.web.mapper.sys.*;
import com.hongshu.web.service.sys.ISysSystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 系统配置关系表 服务实现类
 *
 * @author: hongshu
 */
@Slf4j
@Service
public class SysSystemConfigServiceImpl implements ISysSystemConfigService {

    @Autowired
    private SysSystemConfigMapper systemConfigMapper;
    @Autowired
    private SysOssConfigMapper ossConfigMapper;
    @Autowired
    private SysSmsConfigMapper smsConfigMapper;
    @Autowired
    private SysAlipayConfigMapper alipayConfigMapper;
    @Autowired
    private SysBlacklistIpConfigMapper blacklistIpMapper;


    @Override
    public ConfigDataDTO getAllConfigData() {
        ConfigDataDTO configData = new ConfigDataDTO();
        // 获取各种配置
        configData.setWebsite(this.getWebsiteConfig());
        configData.setSystem(this.getSystemConfig());
//        configData.setLocal(this.getLocalConfig());
        configData.setOss(this.getOssConfig());
        configData.setSms(this.getSmsConfig());
        configData.setAlipay(this.getAlipayConfig());
        configData.setCaptcha(this.getCaptchaConfig());
        configData.setAmap(this.getAmapConfig());
        configData.setDemoAccount(this.getDemoAccountConfig());
        configData.setDemoSite(this.getDemoSiteConfig());
        configData.setBlacklist(this.getBlacklistConfig());

        return configData;
    }

    // 更新网站配置
    @Override
    @Transactional
    public void updateWebsiteConfig(WebsiteConfigDTO websiteConfig) {
        try {
            Map<ConfigKeyEnum, String> configMap = new HashMap<>();
            configMap.put(ConfigKeyEnum.WEBSITE_LOGO, websiteConfig.getLogo());
            configMap.put(ConfigKeyEnum.WEBSITE_NAME, websiteConfig.getName());
            configMap.put(ConfigKeyEnum.WEBSITE_AUTHOR, websiteConfig.getAuthor());
            configMap.put(ConfigKeyEnum.WEBSITE_TITLE, websiteConfig.getTitle());
            configMap.put(ConfigKeyEnum.WEBSITE_DESCRIPTION, websiteConfig.getDescription());
            configMap.put(ConfigKeyEnum.WEBSITE_AI, websiteConfig.getAiUrl());
            configMap.put(ConfigKeyEnum.WEBSITE_COPYRIGHT, websiteConfig.getCopyright());
            configMap.put(ConfigKeyEnum.WEBSITE_WECHAT_QR_CODE, websiteConfig.getWechatQrCode());
            configMap.put(ConfigKeyEnum.WEBSITE_FOLLOW_US, websiteConfig.getFollowUs());
            configMap.put(ConfigKeyEnum.WEBSITE_ALIPAY_REWARD_QR_CODE, websiteConfig.getAlipayRewardQrCode());
            configMap.put(ConfigKeyEnum.WEBSITE_WECHAT_REWARD_QR_CODE, websiteConfig.getWechatRewardQrCode());

            this.updateConfigValues(configMap);
        } catch (Exception e) {
            log.error("更新网站配置失败", e);
        }
    }

    // 更新系统配置
    @Override
    @Transactional
    public void updateSystemConfig(SystemConfigDTO systemConfig) {
        Map<ConfigKeyEnum, String> configMap = new HashMap<>();
        configMap.put(ConfigKeyEnum.OSS_TYPE, systemConfig.getOssType());
        configMap.put(ConfigKeyEnum.SMS_PRIMARY, systemConfig.getSmsPrimary());
        configMap.put(ConfigKeyEnum.MQ_TYPE, systemConfig.getMqType());
        configMap.put(ConfigKeyEnum.QUERY_PRIMARY, systemConfig.getQueryPrimary());
        configMap.put(ConfigKeyEnum.AMAP_ENABLED, systemConfig.getAmapEnabled());
        configMap.put(ConfigKeyEnum.BLACKLIST_ENABLED, systemConfig.getBlacklistEnabled() ? "1" : "0");
        configMap.put(ConfigKeyEnum.CONTENT_AUDIT_ENABLED,
                systemConfig.getContentAuditEnabled() != null && systemConfig.getContentAuditEnabled() ? "1" : "0");
        configMap.put(ConfigKeyEnum.PRODUCT_AUDIT_ENABLED,
                systemConfig.getProductAuditEnabled() != null && systemConfig.getProductAuditEnabled() ? "1" : "0");
        configMap.put(ConfigKeyEnum.USER_AUDIT_ENABLED,
                systemConfig.getUserAuditEnabled() != null && systemConfig.getUserAuditEnabled() ? "1" : "0");

        this.updateConfigValues(configMap);
    }

    // 更新本地存储配置
    @Override
    @Transactional
    public void updateLocalConfig(LocalConfigDTO localConfig) {
        Map<ConfigKeyEnum, String> configMap = new HashMap<>();
        configMap.put(ConfigKeyEnum.FILE_UPLOAD_PATH, localConfig.getFileUploadPath());
        configMap.put(ConfigKeyEnum.LOCAL_PICTURE_BASE_URL, localConfig.getLocalPictureBaseUrl());
        configMap.put(ConfigKeyEnum.LOCAL_STORAGE_ENABLED, localConfig.getIsEnabled() ? "1" : "0");

        this.updateConfigValues(configMap);
    }

    // 更新OSS配置
    @Override
    @Transactional
    public void updateOssConfig(String provider, OssConfigDTO ossConfig) {
        // 如果是本地存储，使用系统配置表
        if ("local".equals(provider)) {
            this.updateLocalConfigAsOss(ossConfig);
            return;
        }
        LambdaQueryWrapper<WebOssConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WebOssConfig::getProvider, provider);
        WebOssConfig config = ossConfigMapper.selectOne(wrapper);

        if (config == null) {
            config = new WebOssConfig();
            config.setProvider(provider);
        }

        // 根据服务商类型进行字段映射
        OssProviderEnum providerEnum = OssProviderEnum.valueOf(provider.toUpperCase());
        switch (providerEnum) {
            case MINIO:
                config.setEndpoint(ossConfig.getUrl());  // Minio的url存储在endpoint字段
                break;
            case ALIYUN:
                config.setAccessKey(ossConfig.getAccessKeyId());  // 阿里云的accessKeyId存储在accessKey字段
                config.setSecretKey(ossConfig.getAccessKeySecret()); // 阿里云的accessKeySecret存储在secretKey字段
                break;
            case TENCENT:
                config.setAccessKey(ossConfig.getOssKeyId());  // 腾讯云的ossKeyId存储在accessKey字段
                config.setSecretKey(ossConfig.getOssKeySecret()); // 腾讯云的ossKeySecret存储在secretKey字段
                break;
            case QINIUYUN:
                config.setAccessKey(ossConfig.getAccessKey());
                config.setSecretKey(ossConfig.getSecretKey());
                break;
            case LOCAL:
                // 本地存储已经在上面处理了，这里不需要处理
                break;
        }
        config.setDomain(ossConfig.getDomain());
        config.setBucketName(ossConfig.getBucketName());
        config.setIsEnabled(ossConfig.getIsEnabled());
        config.setEndpoint(ossConfig.getEndpoint());
        config.setRegion(ossConfig.getRegion());
        config.setIsEnabled(ossConfig.getIsEnabled());
        config.setUpdateTime(new Date());

        if (config.getId() == null) {
            ossConfigMapper.insert(config);
        } else {
            ossConfigMapper.updateById(config);
        }
    }

    // 新增方法：将OSS格式的本地存储配置更新到系统配置表
    private void updateLocalConfigAsOss(OssConfigDTO ossConfig) {
        Map<ConfigKeyEnum, String> configMap = new HashMap<>();
        configMap.put(ConfigKeyEnum.FILE_UPLOAD_PATH, ossConfig.getUrl()); // url存储文件路径
        configMap.put(ConfigKeyEnum.LOCAL_PICTURE_BASE_URL, ossConfig.getDomain()); // domain存储域名
        configMap.put(ConfigKeyEnum.LOCAL_STORAGE_ENABLED, ossConfig.getIsEnabled() ? "1" : "0");

        this.updateConfigValues(configMap);
    }

    // 更新短信配置
    @Override
    @Transactional
    public void updateSmsConfig(String provider, SmsConfigDTO smsConfig) {
        LambdaQueryWrapper<WebSmsConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WebSmsConfig::getProvider, provider);
        WebSmsConfig config = smsConfigMapper.selectOne(wrapper);

        if (config == null) {
            config = new WebSmsConfig();
            config.setProvider(provider);
        }

        // 根据服务商类型进行字段映射
        SmsProviderEnum providerEnum = SmsProviderEnum.valueOf(provider.toUpperCase());
        switch (providerEnum) {
            case TENCENT:
                config.setAccessKey(smsConfig.getSecretId());  // 腾讯云的secretId存储在accessKey字段
                config.setTemplateCode(smsConfig.getTemplateId()); // 腾讯云的templateId存储在templateCode字段
                break;
            case YUNPIAN:
                config.setAccessKey(smsConfig.getApiKey());  // 云片的apiKey存储在accessKey字段
                break;
            case ALIYUN:
                config.setAccessKey(smsConfig.getAccessKey());
                config.setTemplateCode(smsConfig.getTemplateCode());
                break;
        }
        config.setSecretKey(smsConfig.getSecretKey());
        config.setSignName(smsConfig.getSignName());
        config.setIsPrimary(smsConfig.getIsPrimary());
        config.setIsSecondary(smsConfig.getIsSecondary());
        config.setStatus(smsConfig.getStatus());
        config.setSdkAppId(smsConfig.getSdkAppId());
        config.setRegion(smsConfig.getRegion());
        config.setUpdateTime(new Date());

        if (config.getId() == null) {
            smsConfigMapper.insert(config);
        } else {
            smsConfigMapper.updateById(config);
        }
    }

    // 更新支付宝配置
    @Override
    @Transactional
    public void updateAlipayConfig(AlipayConfigDTO alipayConfig) {
        LambdaQueryWrapper<WebAlipayConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.last("LIMIT 1");
        WebAlipayConfig config = alipayConfigMapper.selectOne(wrapper);

        if (config == null) {
            config = new WebAlipayConfig();
        }

        config.setPid(alipayConfig.getPid());
        config.setAppId(alipayConfig.getAppId());
        config.setMerchantPrivateKey(alipayConfig.getMerchantPrivateKey());
        config.setAlipayPublicKey(alipayConfig.getAlipayPublicKey());
        config.setNotifyUrl(alipayConfig.getNotifyUrl());
        config.setReturnUrl(alipayConfig.getReturnUrl());
        config.setSignType(alipayConfig.getSignType());
        config.setCharset(alipayConfig.getCharset());
        config.setGatewayUrl(alipayConfig.getGatewayUrl());
        config.setIsEnabled(alipayConfig.getIsEnabled());
        config.setUpdateTime(new Date());

        if (config.getId() == null) {
            alipayConfigMapper.insert(config);
        } else {
            alipayConfigMapper.updateById(config);
        }
    }

    // 更新验证码配置
    @Override
    @Transactional
    public void updateCaptchaConfig(CaptchaConfigDTO captchaConfig) {
        Map<ConfigKeyEnum, String> configMap = new HashMap<>();
        configMap.put(ConfigKeyEnum.CAPTCHA_CACHE_TYPE, captchaConfig.getCacheType());
        configMap.put(ConfigKeyEnum.CAPTCHA_TYPE, captchaConfig.getType());
        configMap.put(ConfigKeyEnum.CAPTCHA_WATER_MARK, captchaConfig.getWaterMark());
        configMap.put(ConfigKeyEnum.CAPTCHA_SLIP_OFFSET, String.valueOf(captchaConfig.getSlipOffset()));
        configMap.put(ConfigKeyEnum.CAPTCHA_AES_STATUS, captchaConfig.getAesStatus() ? "true" : "false");
        configMap.put(ConfigKeyEnum.CAPTCHA_INTERFERENCE_OPTIONS, String.valueOf(captchaConfig.getInterferenceOptions()));
        configMap.put(ConfigKeyEnum.CAPTCHA_JIGSAW, captchaConfig.getJigsaw());
        configMap.put(ConfigKeyEnum.CAPTCHA_PIC_CLICK, captchaConfig.getPicClick());
        configMap.put(ConfigKeyEnum.CAPTCHA_ENABLED, captchaConfig.getIsEnabled() ? "1" : "0");

        this.updateConfigValues(configMap);
    }

    // 更新高德地图配置
    @Override
    @Transactional
    public void updateAmapConfig(AmapConfigDTO amapConfig) {
        Map<ConfigKeyEnum, String> configMap = new HashMap<>();
        configMap.put(ConfigKeyEnum.AMAP_KEY, amapConfig.getKey());
        configMap.put(ConfigKeyEnum.AMAP_SECURITY_KEY, amapConfig.getSecurityKey());
        configMap.put(ConfigKeyEnum.AMAP_ENABLED, amapConfig.getIsEnabled() ? "1" : "0");

        this.updateConfigValues(configMap);
    }

    // 更新演示账号配置
    @Override
    @Transactional
    public void updateDemoAccount(DemoAccountConfigDTO demoAccountConfig) {
        Map<ConfigKeyEnum, String> configMap = new HashMap<>();
        configMap.put(ConfigKeyEnum.DEMO_ACCOUNT_ENABLED, demoAccountConfig.getEnabled() ? "1" : "0");
        configMap.put(ConfigKeyEnum.DEMO_ACCOUNT_USERNAME, demoAccountConfig.getUsername());
        configMap.put(ConfigKeyEnum.DEMO_ACCOUNT_PASSWORD, demoAccountConfig.getPassword());
        configMap.put(ConfigKeyEnum.DEMO_ACCOUNT_DESCRIPTION, demoAccountConfig.getDescription());
        configMap.put(ConfigKeyEnum.DEMO_ACCOUNT_PERMISSIONS,
                demoAccountConfig.getPermissions() != null ?
                        String.join(",", demoAccountConfig.getPermissions()) : "");
        configMap.put(ConfigKeyEnum.DEMO_ACCOUNT_EXPIRE_TIME, demoAccountConfig.getExpireTime());

        this.updateConfigValues(configMap);
    }

    // 更新演示站配置
    @Override
    @Transactional
    public void updateDemoSite(DemoSiteConfigDTO demoSiteConfig) {
        Map<ConfigKeyEnum, String> configMap = new HashMap<>();
        configMap.put(ConfigKeyEnum.DEMO_SITE_ENABLED, demoSiteConfig.getEnabled() ? "1" : "0");
        configMap.put(ConfigKeyEnum.DEMO_SITE_MOBILE_URL, demoSiteConfig.getMobileUrl());
        configMap.put(ConfigKeyEnum.DEMO_SITE_WEB_URL, demoSiteConfig.getWebUrl());
        configMap.put(ConfigKeyEnum.DEMO_SITE_ADMIN_URL, demoSiteConfig.getAdminUrl());
        configMap.put(ConfigKeyEnum.DEMO_SITE_GITEE_URL, demoSiteConfig.getGiteeUrl());
        configMap.put(ConfigKeyEnum.DEMO_SITE_GITHUB_URL, demoSiteConfig.getGithubUrl());
        configMap.put(ConfigKeyEnum.DEMO_SITE_DOC_URL, demoSiteConfig.getDocUrl());
        configMap.put(ConfigKeyEnum.DEMO_SITE_ARCO_ADMIN_URL, demoSiteConfig.getArcoAdminUrl());
        configMap.put(ConfigKeyEnum.DEMO_SITE_DESCRIPTION, demoSiteConfig.getDescription());
        configMap.put(ConfigKeyEnum.DEMO_SITE_ENABLE_STATS, demoSiteConfig.getEnableStats() ? "1" : "0");

        this.updateConfigValues(configMap);
    }

    // 更新黑名单配置
    @Override
    @Transactional
    public void updateBlacklistEnabled(Boolean enabled) {
        updateConfigValue(ConfigKeyEnum.BLACKLIST_ENABLED.getKey(), enabled ? "1" : "0");
    }

    @Override
    @Transactional
    public void addBlacklistItem(BlacklistItemDTO blacklistItemDTO) {
        // 检查IP是否已存在
        WebIpBlacklist existingItem = blacklistIpMapper
                .selectOne(new LambdaQueryWrapper<WebIpBlacklist>()
                        .eq(WebIpBlacklist::getIpAddress, blacklistItemDTO.getIpAddress()));
        if (existingItem != null) {
            throw new RuntimeException("该IP地址已在黑名单中");
        }
        // 创建新的黑名单项
        WebIpBlacklist blacklistItem = new WebIpBlacklist();
        blacklistItem.setIpAddress(blacklistItemDTO.getIpAddress());
        blacklistItem.setReason(blacklistItemDTO.getReason());
        blacklistItem.setStatus("1"); // 1-封禁状态
        blacklistItem.setBanTime(new Date());
        blacklistItem.setCreateTime(new Date());
        blacklistItem.setUpdateTime(new Date());
        // 设置解封时间（如果有）
        if (blacklistItemDTO.getExpireTime() != null) {
            blacklistItem.setExpireTime(blacklistItemDTO.getExpireTime());
        }

        blacklistIpMapper.insert(blacklistItem);
    }

    @Override
    @Transactional
    public void unbanBlacklistItem(Long id) {
        // 查询黑名单项是否存在
        WebIpBlacklist blacklistItem = blacklistIpMapper.selectById(id);
        if (blacklistItem == null) {
            throw new RuntimeException("黑名单项不存在");
        }
        // 检查是否已经是解封状态
        if ("0".equals(blacklistItem.getStatus())) {
            throw new RuntimeException("该IP已经是解封状态");
        }
        // 更新状态为解封
        blacklistItem.setStatus("0"); // 0-已解封
        blacklistItem.setExpireTime(LocalDateTime.now());
        blacklistItem.setUpdateTime(new Date());
        // 更新数据库
        int result = blacklistIpMapper.updateById(blacklistItem);
        if (result <= 0) {
            throw new RuntimeException("解封失败，请重试");
        }
    }

    @Override
    @Transactional
    public void deleteBlacklistItem(Long id) {
        // 查询黑名单项是否存在
        WebIpBlacklist blacklistItem = blacklistIpMapper.selectById(id);
        if (blacklistItem == null) {
            throw new RuntimeException("黑名单项不存在");
        }
        // 检查是否正在封禁状态
        if ("1".equals(blacklistItem.getStatus())) {
            throw new RuntimeException("该IP正在封禁状态，请先解封后再删除");
        }
        // 删除黑名单项
        int result = blacklistIpMapper.deleteById(id);
        if (result <= 0) {
            throw new RuntimeException("删除失败，请重试");
        }
    }

    // 通用的配置更新方法
    private void updateConfigValues(Map<ConfigKeyEnum, String> configMap) {
        for (Map.Entry<ConfigKeyEnum, String> entry : configMap.entrySet()) {
            if (entry.getValue() != null) {
                this.updateConfigValue(entry.getKey().getKey(), entry.getValue());
            }
        }
    }

    // 通用的配置更新方法
    private void updateConfigValue(String configKey, String configValue) {
        LambdaQueryWrapper<WebSystemConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WebSystemConfig::getConfigKey, configKey);
        WebSystemConfig config = systemConfigMapper.selectOne(wrapper);

        if (config != null) {
            config.setConfigValue(configValue);
            config.setUpdateTime(new Date());
            systemConfigMapper.updateById(config);
        } else {
            // 如果配置不存在，创建新的配置
            WebSystemConfig newConfig = new WebSystemConfig();
            newConfig.setConfigKey(configKey);
            newConfig.setConfigValue(configValue);
            newConfig.setConfigGroup("website");
            newConfig.setCreateTime(new Date());
            newConfig.setUpdateTime(new Date());
            systemConfigMapper.insert(newConfig);
        }
    }


    // 获取网站配置
    public WebsiteConfigDTO getWebsiteConfig() {
        List<String> configKeys = ConfigKeyEnum.getWebsiteConfigKeys();
        List<WebSystemConfig> configs = this.getConfigsByKeys(configKeys);

        WebsiteConfigDTO websiteConfig = new WebsiteConfigDTO();
        for (WebSystemConfig config : configs) {
            ConfigKeyEnum configKey = ConfigKeyEnum.fromKey(config.getConfigKey());
            if (configKey != null) {
                switch (configKey) {
                    case WEBSITE_LOGO:
                        websiteConfig.setLogo(config.getConfigValue());
                        break;
                    case WEBSITE_NAME:
                        websiteConfig.setName(config.getConfigValue());
                        break;
                    case WEBSITE_AUTHOR:
                        websiteConfig.setAuthor(config.getConfigValue());
                        break;
                    case WEBSITE_TITLE:
                        websiteConfig.setTitle(config.getConfigValue());
                        break;
                    case WEBSITE_DESCRIPTION:
                        websiteConfig.setDescription(config.getConfigValue());
                        break;
                    case WEBSITE_COPYRIGHT:
                        websiteConfig.setCopyright(config.getConfigValue());
                        break;
                    case WEBSITE_AI:
                        websiteConfig.setAiUrl(config.getConfigValue());
                        break;
                    case WEBSITE_WECHAT_QR_CODE:
                        websiteConfig.setWechatQrCode(config.getConfigValue());
                        break;
                    case WEBSITE_FOLLOW_US:
                        websiteConfig.setFollowUs(config.getConfigValue());
                        break;
                    case WEBSITE_ALIPAY_REWARD_QR_CODE:
                        websiteConfig.setAlipayRewardQrCode(config.getConfigValue());
                        break;
                    case WEBSITE_WECHAT_REWARD_QR_CODE:
                        websiteConfig.setWechatRewardQrCode(config.getConfigValue());
                        break;
                }
            }
        }
        return websiteConfig;
    }

    // 获取系统配置
    public SystemConfigDTO getSystemConfig() {
        List<String> configKeys = ConfigKeyEnum.getSystemConfigKeys();
        List<WebSystemConfig> configs = this.getConfigsByKeys(configKeys);

        SystemConfigDTO systemConfig = new SystemConfigDTO();
        for (WebSystemConfig config : configs) {
            ConfigKeyEnum configKey = ConfigKeyEnum.fromKey(config.getConfigKey());
            if (configKey != null) {
                switch (configKey) {
                    case OSS_TYPE:
                        systemConfig.setOssType(config.getConfigValue());
                        break;
                    case SMS_PRIMARY:
                        systemConfig.setSmsPrimary(config.getConfigValue());
                        break;
                    case MQ_TYPE:
                        systemConfig.setMqType(config.getConfigValue());
                        break;
                    case QUERY_PRIMARY:
                        systemConfig.setQueryPrimary(config.getConfigValue());
                        break;
                    case AMAP_ENABLED:
                        systemConfig.setAmapEnabled(config.getConfigValue());
                        break;
                    case BLACKLIST_ENABLED:
                        systemConfig.setBlacklistEnabled("1".equals(config.getConfigValue()));
                        break;
                    case CONTENT_AUDIT_ENABLED:
                        systemConfig.setContentAuditEnabled("1".equals(config.getConfigValue()));
                        break;
                    case PRODUCT_AUDIT_ENABLED:
                        systemConfig.setProductAuditEnabled("1".equals(config.getConfigValue()));
                        break;
                    case USER_AUDIT_ENABLED:
                        systemConfig.setUserAuditEnabled("1".equals(config.getConfigValue()));
                        break;
                }
            }
        }
        return systemConfig;
    }

    // 获取本地存储配置
    public LocalConfigDTO getLocalConfig() {
        List<String> configKeys = ConfigKeyEnum.getLocalConfigKeys();
        List<WebSystemConfig> configs = this.getConfigsByKeys(configKeys);

        LocalConfigDTO localConfig = new LocalConfigDTO();
        for (WebSystemConfig config : configs) {
            ConfigKeyEnum configKey = ConfigKeyEnum.fromKey(config.getConfigKey());
            if (configKey != null) {
                switch (configKey) {
                    case FILE_UPLOAD_PATH:
                        localConfig.setFileUploadPath(config.getConfigValue());
                        break;
                    case LOCAL_PICTURE_BASE_URL:
                        localConfig.setLocalPictureBaseUrl(config.getConfigValue());
                        break;
                    case LOCAL_STORAGE_ENABLED:
                        localConfig.setIsEnabled("1".equals(config.getConfigValue()));
                        break;
                }
            }
        }
        // 设置默认值
        if (localConfig.getLocalPictureBaseUrl() == null) {
            localConfig.setLocalPictureBaseUrl("http://localhost:8080");
        }
        if (localConfig.getIsEnabled() == null) {
            localConfig.setIsEnabled(false);
        }
        return localConfig;
    }

    // 获取OSS配置
    public Map<String, OssConfigDTO> getOssConfig() {
        List<String> providers = OssProviderEnum.getAllCodes();

        LambdaQueryWrapper<WebOssConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(WebOssConfig::getProvider, providers);
        List<WebOssConfig> configs = ossConfigMapper.selectList(wrapper);

        Map<String, OssConfigDTO> ossConfigMap = new HashMap<>();
        // 处理本地存储配置（从系统配置表获取）
        OssConfigDTO localConfig = this.getLocalConfigAsOss();
        if (localConfig != null) {
            ossConfigMap.put("local", localConfig);
        }
        for (WebOssConfig config : configs) {
            OssConfigDTO dto = OssConfigDTO.builder()
                    .domain(config.getDomain())
                    .accessKey(config.getAccessKey())
                    .secretKey(config.getSecretKey())
                    .bucketName(config.getBucketName())
                    .isEnabled(config.getIsEnabled())
                    .endpoint(config.getEndpoint())
                    .region(config.getRegion())
                    .build();

            // 根据服务商类型进行字段映射
            OssProviderEnum provider = OssProviderEnum.valueOf(config.getProvider().toUpperCase());
            switch (provider) {
                case MINIO:
                    dto.setUrl(config.getEndpoint());  // Minio的url从endpoint字段获取
                    break;
                case ALIYUN:
                    dto.setAccessKeyId(config.getAccessKey());  // 阿里云的accessKeyId从accessKey字段获取
                    dto.setAccessKeySecret(config.getSecretKey()); // 阿里云的accessKeySecret从secretKey字段获取
                    break;
                case TENCENT:
                    dto.setOssKeyId(config.getAccessKey());  // 腾讯云的ossKeyId从accessKey字段获取
                    dto.setOssKeySecret(config.getSecretKey()); // 腾讯云的ossKeySecret从secretKey字段获取
                    break;
                case QINIUYUN:
                    // 七牛云不需要特殊处理
                    break;
                case LOCAL:
                    // 本地存储已经在上面处理了，这里跳过
                    continue;
            }
            ossConfigMap.put(config.getProvider(), dto);
        }
        return ossConfigMap;
    }

    // 新增方法：将本地存储配置转换为OSS配置格式
    private OssConfigDTO getLocalConfigAsOss() {
        List<String> configKeys = ConfigKeyEnum.getLocalConfigKeys();
        List<WebSystemConfig> configs = this.getConfigsByKeys(configKeys);

        OssConfigDTO localConfig = new OssConfigDTO();
        for (WebSystemConfig config : configs) {
            ConfigKeyEnum configKey = ConfigKeyEnum.fromKey(config.getConfigKey());
            if (configKey != null) {
                switch (configKey) {
                    case FILE_UPLOAD_PATH:
                        localConfig.setUrl(config.getConfigValue()); // 使用url字段存储路径
                        break;
                    case LOCAL_PICTURE_BASE_URL:
                        localConfig.setDomain(config.getConfigValue()); // 使用domain字段存储域名
                        break;
                    case LOCAL_STORAGE_ENABLED:
                        localConfig.setIsEnabled("1".equals(config.getConfigValue()));
                        break;
                }
            }
        }
        // 设置默认值
        if (localConfig.getDomain() == null) {
            localConfig.setDomain("http://localhost:8080");
        }
        if (localConfig.getIsEnabled() == null) {
            localConfig.setIsEnabled(false);
        }
        return localConfig;
    }

    // 获取OSS配置
    public OssConfigDTO getOssConfig(String provider) {
        // 根据provider查询对应的OSS配置
        WebOssConfig config = ossConfigMapper
                .selectOne(new LambdaQueryWrapper<WebOssConfig>()
                        .eq(WebOssConfig::getProvider, provider));
        if (config == null) {
            log.warn("未找到OSS配置: " + provider);
            return null;
        }
        // 构建DTO
        OssConfigDTO dto = OssConfigDTO.builder()
                .domain(config.getDomain())
                .accessKey(config.getAccessKey())
                .secretKey(config.getSecretKey())
                .bucketName(config.getBucketName())
                .isEnabled(config.getIsEnabled())
                .endpoint(config.getEndpoint())
                .region(config.getRegion())
                .build();
        // 根据服务商类型进行字段映射
        try {
            OssProviderEnum providerEnum = OssProviderEnum.valueOf(config.getProvider().toUpperCase());
            switch (providerEnum) {
                case MINIO:
                    dto.setUrl(config.getEndpoint());  // Minio的url从endpoint字段获取
                    break;
                case ALIYUN:
                    dto.setAccessKeyId(config.getAccessKey());  // 阿里云的accessKeyId从accessKey字段获取
                    dto.setAccessKeySecret(config.getSecretKey()); // 阿里云的accessKeySecret从secretKey字段获取
                    break;
                case TENCENT:
                    dto.setOssKeyId(config.getAccessKey());  // 腾讯云的ossKeyId从accessKey字段获取
                    dto.setOssKeySecret(config.getSecretKey()); // 腾讯云的ossKeySecret从secretKey字段获取
                    break;
                case QINIUYUN:
                    // 七牛云不需要特殊处理
                    break;
            }
        } catch (IllegalArgumentException e) {
            log.error("不支持的OSS服务商类型: " + config.getProvider());
        }
        return dto;
    }

    // 获取短信配置
    public Map<String, SmsConfigDTO> getSmsConfig() {
        List<String> providers = SmsProviderEnum.getAllCodes();

        LambdaQueryWrapper<WebSmsConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(WebSmsConfig::getProvider, providers);
        List<WebSmsConfig> configs = smsConfigMapper.selectList(wrapper);

        Map<String, SmsConfigDTO> smsConfigMap = new HashMap<>();
        for (WebSmsConfig config : configs) {
            SmsConfigDTO dto = SmsConfigDTO.builder()
                    .accessKey(config.getAccessKey())
                    .secretKey(config.getSecretKey())
                    .signName(config.getSignName())
                    .templateCode(config.getTemplateCode())
                    .isPrimary(config.getIsPrimary())
                    .isSecondary(config.getIsSecondary())
                    .status(config.getStatus())
                    .sdkAppId(config.getSdkAppId())
                    .region(config.getRegion())
                    .build();

            // 根据服务商类型进行字段映射
            SmsProviderEnum provider = SmsProviderEnum.valueOf(config.getProvider().toUpperCase());
            switch (provider) {
                case TENCENT:
                    dto.setSecretId(config.getAccessKey());  // 腾讯云的secretId从accessKey字段获取
                    dto.setTemplateId(config.getTemplateCode()); // 腾讯云的templateId从templateCode字段获取
                    break;
                case YUNPIAN:
                    dto.setApiKey(config.getAccessKey());  // 云片的apiKey从accessKey字段获取
                    break;
                case ALIYUN:
                    // 阿里云不需要特殊处理
                    break;
            }
            smsConfigMap.put(config.getProvider(), dto);
        }
        return smsConfigMap;
    }

    // 获取支付宝配置
    public AlipayConfigDTO getAlipayConfig() {
        LambdaQueryWrapper<WebAlipayConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.last("LIMIT 1");
        WebAlipayConfig config = alipayConfigMapper.selectOne(wrapper);

        if (config != null) {
            return AlipayConfigDTO.builder()
                    .pid(config.getPid())
                    .appId(config.getAppId())
                    .merchantPrivateKey(config.getMerchantPrivateKey())
                    .alipayPublicKey(config.getAlipayPublicKey())
                    .notifyUrl(config.getNotifyUrl())
                    .returnUrl(config.getReturnUrl())
                    .signType(config.getSignType())
                    .charset(config.getCharset())
                    .gatewayUrl(config.getGatewayUrl())
                    .isEnabled(config.getIsEnabled())
                    .build();
        }
        return new AlipayConfigDTO();
    }

    // 获取验证码配置
    public CaptchaConfigDTO getCaptchaConfig() {
        List<String> configKeys = ConfigKeyEnum.getCaptchaConfigKeys();
        List<WebSystemConfig> configs = this.getConfigsByKeys(configKeys);

        CaptchaConfigDTO captchaConfig = new CaptchaConfigDTO();
        for (WebSystemConfig config : configs) {
            ConfigKeyEnum configKey = ConfigKeyEnum.fromKey(config.getConfigKey());
            if (configKey != null) {
                switch (configKey) {
                    case CAPTCHA_CACHE_TYPE:
                        captchaConfig.setCacheType(config.getConfigValue());
                        break;
                    case CAPTCHA_TYPE:
                        captchaConfig.setType(config.getConfigValue());
                        break;
                    case CAPTCHA_WATER_MARK:
                        captchaConfig.setWaterMark(config.getConfigValue());
                        break;
                    case CAPTCHA_SLIP_OFFSET:
                        captchaConfig.setSlipOffset(Integer.valueOf(config.getConfigValue()));
                        break;
                    case CAPTCHA_AES_STATUS:
                        captchaConfig.setAesStatus("true".equals(config.getConfigValue()));
                        break;
                    case CAPTCHA_INTERFERENCE_OPTIONS:
                        captchaConfig.setInterferenceOptions(Integer.valueOf(config.getConfigValue()));
                        break;
                    case CAPTCHA_JIGSAW:
                        captchaConfig.setJigsaw(config.getConfigValue());
                        break;
                    case CAPTCHA_PIC_CLICK:
                        captchaConfig.setPicClick(config.getConfigValue());
                        break;
                    case CAPTCHA_ENABLED:
                        captchaConfig.setIsEnabled("1".equals(config.getConfigValue()));
                        break;
                }
            }
        }
        return captchaConfig;
    }

    // 获取高德地图配置
    public AmapConfigDTO getAmapConfig() {
        List<String> configKeys = ConfigKeyEnum.getAmapConfigKeys();
        List<WebSystemConfig> configs = this.getConfigsByKeys(configKeys);

        AmapConfigDTO amapConfig = new AmapConfigDTO();
        for (WebSystemConfig config : configs) {
            ConfigKeyEnum configKey = ConfigKeyEnum.fromKey(config.getConfigKey());
            if (configKey != null) {
                switch (configKey) {
                    case AMAP_KEY:
                        amapConfig.setKey(config.getConfigValue());
                        break;
                    case AMAP_SECURITY_KEY:
                        amapConfig.setSecurityKey(config.getConfigValue());
                        break;
                    case AMAP_ENABLED:
                        amapConfig.setIsEnabled("1".equals(config.getConfigValue()));
                        break;
                }
            }
        }
        return amapConfig;
    }

    // 获取演示账号配置
    public DemoAccountConfigDTO getDemoAccountConfig() {
        List<String> configKeys = ConfigKeyEnum.getDemoAccountConfigKeys();
        List<WebSystemConfig> configs = this.getConfigsByKeys(configKeys);

        DemoAccountConfigDTO demoAccountConfig = new DemoAccountConfigDTO();
        for (WebSystemConfig config : configs) {
            ConfigKeyEnum configKey = ConfigKeyEnum.fromKey(config.getConfigKey());
            if (configKey != null) {
                switch (configKey) {
                    case DEMO_ACCOUNT_ENABLED:
                        demoAccountConfig.setEnabled("1".equals(config.getConfigValue()));
                        break;
                    case DEMO_ACCOUNT_USERNAME:
                        demoAccountConfig.setUsername(config.getConfigValue());
                        break;
                    case DEMO_ACCOUNT_PASSWORD:
                        demoAccountConfig.setPassword(config.getConfigValue());
                        break;
                    case DEMO_ACCOUNT_DESCRIPTION:
                        demoAccountConfig.setDescription(config.getConfigValue());
                        break;
                    case DEMO_ACCOUNT_PERMISSIONS:
                        if (StringUtils.isNotBlank(config.getConfigValue())) {
                            demoAccountConfig.setPermissions(Arrays.asList(config.getConfigValue().split(",")));
                        } else {
                            demoAccountConfig.setPermissions(new ArrayList<>());
                        }
                        break;
                    case DEMO_ACCOUNT_EXPIRE_TIME:
                        demoAccountConfig.setExpireTime(config.getConfigValue());
                        break;
                }
            }
        }
        // 设置默认值
        if (demoAccountConfig.getEnabled() == null) {
            demoAccountConfig.setEnabled(false);
        }
        if (demoAccountConfig.getPermissions() == null) {
            demoAccountConfig.setPermissions(new ArrayList<>());
        }
        return demoAccountConfig;
    }

    // 获取演示站配置
    public DemoSiteConfigDTO getDemoSiteConfig() {
        List<String> configKeys = ConfigKeyEnum.getDemoSiteConfigKeys();
        List<WebSystemConfig> configs = this.getConfigsByKeys(configKeys);

        DemoSiteConfigDTO demoSiteConfig = new DemoSiteConfigDTO();
        for (WebSystemConfig config : configs) {
            ConfigKeyEnum configKey = ConfigKeyEnum.fromKey(config.getConfigKey());
            if (configKey != null) {
                switch (configKey) {
                    case DEMO_SITE_ENABLED:
                        demoSiteConfig.setEnabled("1".equals(config.getConfigValue()));
                        break;
                    case DEMO_SITE_MOBILE_URL:
                        demoSiteConfig.setMobileUrl(config.getConfigValue());
                        break;
                    case DEMO_SITE_WEB_URL:
                        demoSiteConfig.setWebUrl(config.getConfigValue());
                        break;
                    case DEMO_SITE_ADMIN_URL:
                        demoSiteConfig.setAdminUrl(config.getConfigValue());
                        break;
                    case DEMO_SITE_GITEE_URL:
                        demoSiteConfig.setGiteeUrl(config.getConfigValue());
                        break;
                    case DEMO_SITE_GITHUB_URL:
                        demoSiteConfig.setGithubUrl(config.getConfigValue());
                        break;
                    case DEMO_SITE_DOC_URL:
                        demoSiteConfig.setDocUrl(config.getConfigValue());
                        break;
                    case DEMO_SITE_ARCO_ADMIN_URL:
                        demoSiteConfig.setArcoAdminUrl(config.getConfigValue());
                        break;
                    case DEMO_SITE_DESCRIPTION:
                        demoSiteConfig.setDescription(config.getConfigValue());
                        break;
                    case DEMO_SITE_ENABLE_STATS:
                        demoSiteConfig.setEnableStats("1".equals(config.getConfigValue()));
                        break;
                }
            }
        }
        // 设置默认值
        if (demoSiteConfig.getEnabled() == null) {
            demoSiteConfig.setEnabled(false);
        }
        if (demoSiteConfig.getEnableStats() == null) {
            demoSiteConfig.setEnableStats(false);
        }
        return demoSiteConfig;
    }

    // 获取黑名单配置
    @Override
    public BlacklistConfigDTO getBlacklistConfig() {
        // 获取黑名单开关状态
        LambdaQueryWrapper<WebSystemConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WebSystemConfig::getConfigKey, ConfigKeyEnum.BLACKLIST_ENABLED.getKey());
        WebSystemConfig blacklistEnabled = systemConfigMapper.selectOne(wrapper);

        BlacklistConfigDTO blacklistConfig = new BlacklistConfigDTO();
        blacklistConfig.setEnabled("1".equals(blacklistEnabled != null ? blacklistEnabled.getConfigValue() : "0"));

        // 如果黑名单启用，获取黑名单列表
        if (blacklistConfig.getEnabled()) {
            List<WebIpBlacklist> blacklistItems = blacklistIpMapper.selectList(null);
            List<BlacklistItemDTO> itemDTOs = blacklistItems.stream()
                    .map(item -> BlacklistItemDTO.builder()
                            .id(item.getId())
                            .ipAddress(item.getIpAddress())
                            .reason(item.getReason())
                            .status(item.getStatus())
                            .banTime(item.getBanTime())
                            .expireTime(item.getExpireTime())
                            .build())
                    .collect(Collectors.toList());
            blacklistConfig.setList(itemDTOs);
        } else {
            blacklistConfig.setList(new ArrayList<>());
        }
        return blacklistConfig;
    }

    // 通用的配置查询方法
    private List<WebSystemConfig> getConfigsByKeys(List<String> configKeys) {
        LambdaQueryWrapper<WebSystemConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(WebSystemConfig::getConfigKey, configKeys);
        return systemConfigMapper.selectList(wrapper);
    }
}
